<template>
  <div class="_wz_cent_main" style="height: 100%;width: 100%;" :style="{backgroundColor:!!chartsData ? (!!chartsData.backColor ? chartsData.backColor : '#fff') : '#fff'}">
    <div :id="!!chartsData ? (!!chartsData.id ? chartsData.id : '唯一值id') : '唯一值id'" style="height: 100%;width: 100%;"></div>


  </div>
</template>
<script>


import {getCurrentInstance,nextTick,reactive, toRefs,toRef,onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted, ref,defineComponent,toRaw,watch} from 'vue'

export default defineComponent({
  name: 'barChart',//组件名称
  components: {},//组件引用
  props: ['dataConfiguration'],//接收来自父组件的数据
  setup (props) {

    // 变量全局化
    const echarts = getCurrentInstance()?.appContext.config.globalProperties.$echarts

    //监听
    watch(() => props.dataConfiguration,(news, old) => {
      nextTick(()=>{
        windowChanges()
      })
    },{deep: true});


    //变量
    const state = reactive({
      chartsYu:null,
      chartsData:null,
    });

    //窗口改变
    const  windowChanges = ()=>{
      // debugger;
      if(state.chartsYu != null && state.chartsYu != "" && state.chartsYu != undefined){
        toRaw(state.chartsYu).resize();
      }else{

        nextTick(()=>{
          initFun(state.chartsData);
        })
      }
    };

    //统计渲染图表
    const initFun = (data) => {

      // chartsYu
      if (state.chartsYu != null && state.chartsYu != "" && state.chartsYu != undefined) {
        toRaw(state.chartsYu).dispose();//销毁
      }
      var chartDom = document.getElementById(!!data.id ? data.id : '唯一值id');
      state.chartsYu = echarts.init(chartDom);
      var color = !!data.colors ? data.colors : [];
      // <Option value="0">隐藏</Option>
      // <Option value="1">上居中</Option>
      // <Option value="2">上居右</Option>
      // <Option value="3">上居左</Option>
      // <Option value="4">下居中</Option>
      // <Option value="5">下居右</Option>
      // <Option value="6">下居左</Option>
      // <Option value="7">左居中</Option>
      // <Option value="8">左居右</Option>
      // <Option value="9">左居左</Option>
      // <Option value="10">右居中</Option>
      // <Option value="11">右居右</Option>
      // <Option value="12">右居左</Option>

      let legend = {};
      if(!!data.legend){
        if(data.legend == 1){//上居中
          legend.y = "top";
          legend.x = "center";
        }else if(data.legend == 2){//上居右
          legend.y = "top";
          legend.x = "right";
        }else if(data.legend == 3){//上居左
          legend.y = "top";
          legend.x = "left";
        }else if(data.legend == 4){//下居中
          legend.y = "bottom";
          legend.x = "center";
        }else if(data.legend == 5){//下居右
          legend.y = "bottom";
          legend.x = "right";
        }else if(data.legend == 6){//下居左
          legend.y = "bottom";
          legend.x = "left";
        }else if(data.legend == 7){//左居中
          legend.y = "center";
          legend.x = "left";
          legend.orient = 'vertical';
        }else if(data.legend == 8){//左居上
          legend.y = "top";
          legend.x = "left";
          legend.orient = 'vertical';
        }else if(data.legend == 9){//左居下
          legend.y = "bottom";
          legend.x = "left";
          legend.orient = 'vertical';
        }else if(data.legend == 10){//右居中
          legend.y = "center";
          legend.x = "right";
          legend.orient = 'vertical';
        }else if(data.legend == 11){//右居上
          legend.y = "top";
          legend.x = "right";
          legend.orient = 'vertical';
        }else if(data.legend == 12){//右居下
          legend.y = "bottom";
          legend.x = "right";
          legend.orient = 'vertical';
        }
      }else{//隐藏
        legend.show = false;
      }


      //图例数据 设置
      legend.data = [];//type
      if(!!data.legendColor){
        legend.textStyle = {
          color:data.legendColor
        }
      }

      let series = [],xAxisData = [];//
      data.dataList.forEach(function(k,i){
        //xAxisData
        var type = false;
        for(var io = 0 ;io < xAxisData.length;io++){
          if(xAxisData[io] == k.name){
            type = true;
            // return false;
          }
        }
        if(!type){
          xAxisData.push(k.name)
        }

        //series
        var xType = false;
        for(var io = 0 ;io < series.length;io++){
          if(series[io].name == k.type){
            series[io].data.push(k.value)
            xType = true;
            // return false;
          }
        }
        if(!xType){
          var zData = {
            name: k.type,
            type: 'bar',
            data: [k.value],
            areaStyle: {},
          }
          if(data.stackingTiling != 'Tiling'){// 堆叠
            zData.stack = 'Total'
          }
          if(!!data.size){// 柱子大小
            zData.barWidth = data.size
          }
          if(!!data.barGap){// 子柱子间隙
            zData.barGap = data.barGap
          }
          if(!!data.barCategoryGap){// 每组柱子间隙
            zData.barCategoryGap = data.barCategoryGap
          }
          if(!!data.showBackground){// 是否带背景
            zData.showBackground = data.showBackground
          }
          if(!!data.markPoint){// 最大最小标记
            zData.markPoint = {
              data: [
                { type: 'max', name: 'Max' },
                { type: 'min', name: 'Min' }
              ]
            }
          }
          if(!!data.markLine){// 平均值
            zData.markLine = {
              data: [{ type: 'average', name: 'Avg' }]
            }
          }
          series.push(zData)
          legend.data.push(k.type)
        }

      })



      let option = {
        color:color,
        title: {
          text: ''
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: legend,
        grid: {
          top:!!data.top ? data.top + data.marginUnit : 0,
          left: !!data.left ? data.left + data.marginUnit : 0,
          right: !!data.right ? data.right + data.marginUnit : 0,
          bottom: !!data.bottom ? data.bottom + data.marginUnit : 0,
          containLabel: true
        },
        yAxis: {
          type: 'category',
          "splitLine": {
            "show": !!data.xShow ? data.xShow : false
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: !!data.xColor ? data.xColor : "#e0e6f1"
            }
          },
          data: xAxisData,//legend.data
        },
        xAxis: {
          type: 'value',
          "axisLine":{       //y轴
            "show":!!data.yShow ? data.yShow : false
          },
          "axisTick":{       //y轴刻度线
            "show":!!data.yShow ? data.yShow : false
          },
          "splitLine": {     //网格线
            "show": !!data.yShow ? data.yShow : false
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: !!data.xColor ? data.xColor : "#e0e6f1"
            }
          },
        },
        series: series
      };

      //点击事件
      state.chartsYu.on('click', function (param) {
        //获取自定义变量barIds的值,barIds要和option的series里自定义的一样
        if(!!data.chartsClick){
          data.chartsClick(param);
        }
        // console.log(param)

      });

      toRaw(state.chartsYu).setOption(option);
      toRaw(state.chartsYu).resize();

    }

    //数据初始化
    const dataInit = (data) => {
      if(!!props.dataConfiguration && props.dataConfiguration.id){
        // state.chartsData = JSON.parse(JSON.stringify(state.dataConfiguration))
        state.chartsData = props.dataConfiguration;
      }else{
        state.chartsData = {
          "id":"barChart",
          "width":'100%',
          "height":'100%',
          "colors":["#2d8cf0","#19be6b","#ff9900","#ed4014","#9b66e6","#3fcece","#4b588d","#b7b83f","#b9783f","#4efd95","#2ebdcc","#375397","#22597e","#2e33d1","#3bd2a6","#95CEFF","#A9FF96","#FFBC75","#AAFFFA","#999EFF","#FF7599","#FDEC6D","#44A9A8","#2D8CF0"],
          "xColor":"#000",
          "yColor":"#000",
          "xShow":true,
          "yShow":true,
          "backColor":"#fff",
          "legendColor":"#000",
          "dataList":[
            {"type":"类型13","name":"名称1","value":20},
            {"type":"类型13","name":"名称2","value":77},
            {"type":"类型13","name":"名称3","value":70},
            {"type":"类型13","name":"名称4","value":22},
            {"type":"类型13","name":"名称5","value":24},
            {"type":"类型13","name":"名称6","value":43},
            {"type":"类型13","name":"名称7","value":49},
            {"type":"类型2","name":"名称1","value":96},
            {"type":"类型2","name":"名称2","value":62},
            {"type":"类型2","name":"名称3","value":87},
            {"type":"类型2","name":"名称4","value":93},
            {"type":"类型2","name":"名称5","value":93},
            {"type":"类型2","name":"名称6","value":51},
            {"type":"类型2","name":"名称7","value":13}
          ],
          "legend":1,
          "marginUnit":"%",
          "top":10,
          "right":4,
          "bottom":4,
          "left":4
        }
      }
    }

    // 其他的生命周期
    onBeforeMount (() => {//beforeMount挂载前状态 // console.log("App ===> 相当于 vue2.x 中 beforeMount")
    })
    onMounted (() => {//mounted 挂载结束状态  // console.log("App ===> 相当于 vue2.x 中 mounted")



      dataInit();
      nextTick(()=>{
        initFun(state.chartsData);
      })


      window.addEventListener('resize', windowChanges, false)
    })



    // 注意，onBeforeUpdate 和 onUpdated 里面不要修改值
    onBeforeUpdate (() => {//beforeUpdate 更新前状态 // console.log("App ===> 相当于 vue2.x 中 beforeUpdate")
    })

    onUpdated (() => {//updated 更新完成状态 // console.log("App ===> 相当于 vue2.x 中 updated")
    })

    onBeforeUnmount (() => {//beforeDestroy 销毁前状态  // console.log("App ===> 相当于 vue2.x 中 beforeDestroy")
    })

    onUnmounted (() => {//destroyed 销毁完成状态  // console.log("App ===> 相当于 vue2.x 中 destroyed")
    })

    return {
      ...toRefs(state),
    }
  }
})


</script>
<style lang="less">

</style>

